﻿using System;

namespace com.susi.util
{
    [Obsolete("Use IDisposaEventer<out T> instead")]
    public interface IDisposaEventer : IDisposable
    {
        event Action onDisposingEvent;
    }

    public interface IDisposaEventer<out T> : IDisposable
    {
        event Action<T> onDisposingTEvent;
    }


    public static class DisposableExtensions
    {
        /// <summary>
        /// Dispose disposable on disposaEventer disposing
        /// return obj is disposable self
        /// </summary>
        public static (IDisposable Disposable,Action Unsubscribe) DisposeOn<T>(this IDisposable disposable, IDisposaEventer<T> disposaEventer)
        {
            void localDispose(T _) => disposable.Dispose();
            disposaEventer.onDisposingTEvent -= localDispose;
            disposaEventer.onDisposingTEvent += localDispose;
            return (disposable, ()=>disposaEventer.onDisposingTEvent -= localDispose);
        }

        /// <summary>
        /// Dispose disposable on disposaEventer disposing
        /// return obj is disposable self
        /// </summary>
        public static (IDisposable Disposable,Action Unsuscribe) DisposeOn(this IDisposable disposable, IDisposaEventer disposaEventer)
        {
            disposaEventer.onDisposingEvent -= disposable.Dispose;
            disposaEventer.onDisposingEvent += disposable.Dispose;
            return (disposable, ()=>disposaEventer.onDisposingEvent -= disposable.Dispose);;
        }
        
        
    }
}